﻿using Ongoal.Quotation.Common;
using Ongoal.Quotation.Cap;
using Ongoal.Quotation.Service;
using Ongoal.Quotation.Service.Common;
using Ongoal.Quotation.Service.Interface;
using Ongoal.Quotation.Service.Model;
using Ongoal.Quotation.Service.Model.basemodel;
using Ongoal.Quotation.Service.Param;
using Ongoal.Quotation.Service.ViewModel;
using SqlSugar;

namespace Ongoal.Quotation.Service
{
    /// <summary>
    /// 用户服务
    /// </summary>
    public class UserService : ServiceBase, IUserService
    {
        private IMessagePublisher _messagePublisher;
        public UserService(IMessagePublisher messagePublisher)
        {
            _messagePublisher = messagePublisher;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool AddUser(ViewUser user, ref string errorMsg)
        {
            DateTime currentTime = DateTime.Now;
            //try
            //{
            checkdata(user, 1);
            //密码加密
            user.Password = Des.Encrypt(user.Password);
            var client = Db!.GetDbContext(string.Empty);

            user.CreatorID = this.CurrentUser!.UserID;
            user.ModifyID = this.CurrentUser!.UserID;
            user.CreateTime = currentTime;
            user.ModifyTime = currentTime;

            //// 方式1
            string tempErrorMsg = null;
            bool result = _messagePublisher.ExecuteDBAndPublish(client.Ado, () =>
            {
                int id = client.Insertable<T_Sys_User>(user).ExecuteReturnIdentity();
                if (id <= 0)
                {
                    tempErrorMsg = "保存用户信息失败";
                    return false;
                }
                user.ID = id;
                if (user.OrgList != null && user.OrgList.Count() > 0)
                {
                    user.OrgList.ForEach(t =>
                    {
                        t.ID = 0;
                        t.UserID = user.ID;
                        t.CreatorID = this.CurrentUser!.UserID;
                        t.CreateTime = DateTime.Now;
                        t.ModifyID = this.CurrentUser!.UserID;
                        t.ModifyTime = DateTime.Now;
                    });
                    if (!client.Insertable<R_User_Org>(user.OrgList).ExecuteCommandIdentityIntoEntity())
                    {
                        tempErrorMsg = "保存用户的组织机构信息失败";
                        return false;
                    }
                }
                _messagePublisher.PublishWithDefaultCallback(MessageConstant.UserBatch, new List<ViewUser>() { user });//推送数据
                return true;
            });
            errorMsg = null;
            if (!result)
            {
                errorMsg = tempErrorMsg;
            }
            return result;



            //client.BeginTran();

            ////方式2
            //int id = client.Insertable<T_Sys_User>(user).ExecuteReturnIdentity();
            //if (id<=0)
            //{
            //    client.RollbackTran();
            //    errorMsg = "保存用户信息失败";
            //    return false;
            //}
            //user.ID = id;
            //if (user.OrgList != null && user.OrgList.Count() > 0)
            //{
            //    user.OrgList.ForEach(t =>
            //    {
            //        t.UserID = user.ID;
            //        t.CreatorID = this.CurrentUser!.UserID;
            //        t.CreateTime = DateTime.Now;
            //        t.ModifyID = this.CurrentUser!.UserID;
            //        t.ModifyTime = DateTime.Now;
            //    });
            //    if (!client.Insertable<R_User_Org>(user.OrgList).ExecuteCommandIdentityIntoEntity())
            //    {
            //        client.RollbackTran();
            //        errorMsg = "保存用户的组织机构信息失败";
            //        return false;
            //    }
            //}
            //client.CommitTran();
            //_messagePublisher.PublishWithDefaultCallback(MessageConstant.User, new List<ViewUser>() { user });//推送数据

            ////以前的代码
            //var userID = client.Insertable<T_Sys_User>(user).ExecuteReturnIdentity();
            //if (userID < 1)
            //{
            //    client.RollbackTran();
            //    throw new Exception("保存用户信息失败");
            //}
            //if (user.OrgList != null && user.OrgList.Count() > 0)
            //{
            //    List<R_User_Org> r_User_Orgs = user.OrgList.Select(t => new R_User_Org()
            //    {
            //        UserID = userID,
            //        OrgID = t.OrgID,
            //        PostID = t.PostID,
            //        CreatorID = this.CurrentUser!.UserID,
            //        CreateTime = DateTime.Now,
            //        ModifyID = this.CurrentUser!.UserID,
            //        ModifyTime = DateTime.Now
            //    }).ToList();
            //    if (client.Insertable<R_User_Org>(r_User_Orgs).ExecuteCommand() != r_User_Orgs.Count())
            //    {
            //        client.RollbackTran();
            //        throw new Exception("保存用户的组织机构信息失败");

            //    }
            //}
            //client.CommitTran();
            //_messagePublisher.PublishWithDefaultCallback(MessageConstant.User, user);//推送数据

            return true;
            //}
            //catch (Exception e)
            //{

            //    throw e;
            //}
        }


        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool EditUser(ViewUser user, ref string errorMsg)
        {
            try
            {
                checkdata(user, 2);
                if (!string.IsNullOrEmpty(user.Password))
                {
                    //密码加密
                    user.Password = Des.Encrypt(user.Password);
                }
                else
                {
                    //如果为赋值密码，那就保持原来的密码
                    var oldInfo = this.Db!.GetDbContext(string.Empty).Queryable<T_Sys_User>().Where(t => t.ID == user.ID).First();
                    if (oldInfo != null)
                    {
                        user.Password = oldInfo.Password;
                    }
                }

                user.ModifyTime = DateTime.Now;
                user.ModifyID = this.CurrentUser?.UserID;
                var client = Db!.GetDbContext(string.Empty);
                string tempErrorMsg = null;
                bool result = _messagePublisher.ExecuteDBAndPublish(client.Ado, () =>
                {
                    if (client.Updateable<T_Sys_User>(user).ExecuteCommand() != 1)
                    {
                        throw new Exception("保存用户信息失败");
                    }
                    if (user.OrgList != null && user.OrgList.Count() > 0)
                    {
                        user.OrgList.ForEach(t =>
                        {
                            t.ID = 0;
                            t.UserID = user.ID;
                            t.CreatorID = this.CurrentUser!.UserID;
                            t.CreateTime = DateTime.Now;
                            t.ModifyID = this.CurrentUser!.UserID;
                            t.ModifyTime = DateTime.Now;
                        });

                        //删除原来的组织机构关系
                        client.Deleteable<R_User_Org>().Where(t => t.UserID == user.ID).ExecuteCommand();
                        //添加新的组织机构关系
                        if (client.Insertable<R_User_Org>(user.OrgList).ExecuteCommand() != user.OrgList.Count)
                        {
                            client.RollbackTran();
                            tempErrorMsg = "保存用户的组织机构信息失败";
                            return false;
                        }
                    }
                    _messagePublisher.PublishWithDefaultCallback(MessageConstant.UserBatch, new List<ViewUser>() { user });//推送数据
                    return true;
                });
                //_messagePublisher.PublishWithDefaultCallback(MessageConstant.User, new List<ViewUser>() { user });//推送数据
                errorMsg = null;
                if (!result)
                {
                    errorMsg = tempErrorMsg;
                }
                return result;
                //client.BeginTran();

                //try
                //{
                //    if (client.Updateable<T_Sys_User>(user).ExecuteCommand() != 1)
                //    {
                //        client.RollbackTran();
                //        throw new Exception("保存用户信息失败");
                //    }
                //    if (user.OrgList != null && user.OrgList.Count() > 0)
                //    {
                //        user.OrgList.ForEach(t =>
                //        {
                //            t.ID = 0;
                //            t.UserID = user.ID;
                //            t.CreatorID = this.CurrentUser!.UserID;
                //            t.CreateTime = DateTime.Now;
                //            t.ModifyID = this.CurrentUser!.UserID;
                //            t.ModifyTime = DateTime.Now;
                //        });

                //        //删除原来的组织机构关系
                //        client.Deleteable<R_User_Org>().Where(t => t.UserID == user.ID).ExecuteCommand();
                //        //添加新的组织机构关系
                //        if (client.Insertable<R_User_Org>(user.OrgList).ExecuteCommand() != user.OrgList.Count)
                //        {
                //            client.RollbackTran();
                //            errorMsg = "保存用户的组织机构信息失败";
                //            return false;
                //        }
                //    }
                //    client.CommitTran();
                //    _messagePublisher.PublishWithDefaultCallback(MessageConstant.User, new List<ViewUser>() { user });//推送数据
                //}
                //    catch(Exception exp)
                //    {
                //        client.RollbackTran();
                //        errorMsg = exp.Message;
                //        return false;
                //    }

                //return true;
                //this.Update<T_Sys_User>(user);
                //return true;
            }
            catch (Exception exp)
            {
                errorMsg = exp.Message;
                return false;
            }
        }

        public bool checkdata(T_Sys_User model, int checktype)
        {
            using (var db = Db.GetDbContext(string.Empty))
            {
                if (checktype == 1) //新增
                {
                    if (db.Queryable<T_Sys_User>().Any(z => z.UserCode == model.UserCode || z.UserName == model.UserName))
                    {
                        throw new Exception("名称或者编码已经存在");
                    }
                }
                else
                { //编辑
                    if (db.Queryable<T_Sys_User>().Any(z => z.ID != model.ID && (z.UserCode == model.UserCode || z.UserName == model.UserName)))
                    {
                        throw new Exception("名称或者编码已经存在");
                    }
                }
                return true;

            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="PaginationEntity"></param>
        /// <param name="usertype"></param>
        /// <param name="orgid"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public object Getuserbypage(PaginationData PaginationEntity, int usertype, int orgid, string keyword)
        {
            using (SqlSugarClient db = Db!.GetDbContext(""))
            {
                List<int> userIDList = new List<int>();
                if (orgid > 0)
                {
                    var orgids = GetChildrens(orgid);
                    userIDList = db.Queryable<R_User_Org>().Where(t => orgids.Contains(t.OrgID)).Select(t => t.UserID).Distinct().ToList();
                    //组织机构下没有挂载人员，直接返回
                    if (userIDList.Count == 0)
                    {
                        PaginationEntity.TotalRecordNum = 0;
                        PaginationEntity.Data = userIDList;
                        return PaginationEntity;
                    }
                }
                var queryable = db.Queryable<T_Sys_User>()
                    .WhereIF(usertype != 0, z => z.UserType == usertype)
                    .WhereIF(orgid > 0, z => userIDList.Contains(z.ID))
                    .WhereIF(!string.IsNullOrEmpty(keyword), z => z.UserName.Contains(keyword) || z.UserCode.Contains(keyword) || z.DisplayName.Contains(keyword));
                PaginationEntity.TotalRecordNum = queryable.Count();
                var datalist = queryable.ToPageList(PaginationEntity.PageIndex, PaginationEntity.PageSize).Select(z => new
                {
                    Sex = z.Sex,
                    AvatarUrl = z.AvatarUrl,
                    Birthday = z.Birthday,
                    CreateTime = z.CreateTime,
                    CreatorID = z.CreatorID,
                    DisplayName = z.DisplayName,
                    Email = z.Email,
                    ID = z.ID,
                    IDCardNO = z.IDCardNO,
                    IsLocked = z.IsLocked,
                    LastLoginTime = z.LastLoginTime,
                    LockTime = z.LockTime,
                    LoginEnable = Convert.ToBoolean(z.LoginEnable),
                    LoginTimes = z.LoginTimes,
                    Mobile = z.Mobile,
                    ModifyID = z.ModifyID,
                    ModifyTime = z.ModifyTime,
                    OnboardingDate = z.OnboardingDate,
                    Password = string.Empty,// Des.Decrypt(z.Password), 管理界面隐藏用户密码
                    QQ = z.QQ,
                    Remark = z.Remark,
                    TenantID = z.TenantID,
                    UserCode = z.UserCode,
                    UserName = z.UserName,
                    UserType = z.UserType,
                    Organize = new List<string>(),
                    Post = new List<string>()
                }).ToList();

                var uids = datalist.Select(s => s.ID).ToList();
                var ops = db.Queryable<R_User_Org>()
                    .LeftJoin<Organize>((uo, o) => uo.OrgID == o.ID)
                    .LeftJoin<Post>((uo, o, p) => uo.PostID == p.ID)
                    .Where(uo => uids.Contains(uo.UserID))
                    .Select((uo, o, p) => new { uid = uo.UserID, Organize = o, Post = p }).ToList();
                foreach (var item in datalist)
                {
                    item.Organize.AddRange(ops.Where(s => s.uid == item.ID).Select(s => s.Organize!.OrgName!).ToList());
                    item.Post.AddRange(ops.Where(s => s.uid == item.ID).Select(s => s.Post!.PostName!).ToList());
                }
                PaginationEntity.Data = datalist;


                return PaginationEntity;
            }
        }

        /// <summary>
        /// 获取组织下边所有子组织
        /// </summary>
        /// <param name="orgid"></param>
        /// <returns></returns>
        public List<int> GetChildrens(int orgid)
        {
            using (SqlSugarClient db = Db!.GetDbContext(""))
            {
                var all = db.Queryable<Organize>().ToList();
                var ids = all.Where(z => z.Deleted == 0 && z.ParentID == orgid).Select(z => z.ID).ToList();
                if (ids.Count == 0)
                {
                    return new List<int> { orgid };
                }
                else
                {
                    ids.Add(orgid);
                    return GetChildrens(ids, all);
                }
            }
        }

        //递归获取所有ID
        public List<int> GetChildrens(List<int> ids, List<Organize> all)
        {

            var childrenids = all.Where(z => z.Deleted == 0 && ids.Contains(Convert.ToInt32(z.ParentID))).Select(z => z.ID).ToList();
            if (childrenids.Count == 0)
            {
                return ids;
            }
            else
            {
                return ids.Union(GetChildrens(childrenids, all)).ToList();
            }
        }
        /// <summary>
        /// 更新当前用户头像
        /// </summary>
        /// <param name="avatarid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public dynamic UpdateAvatar(string avatarid)
        {
            if (string.IsNullOrEmpty(avatarid))
            {
                return new
                {
                    state = false,
                    tip = "头像不可为空"
                };
            }
            var dbclient = this.Db!.GetDbContext(string.Empty);
            var uInfo = dbclient.Queryable<T_Sys_UserInfo>().Where(t => t.ID == this.CurrentUser!.UserID).First();
            if (uInfo != null)
            {
                uInfo.AvatarUrl = avatarid;
                dbclient.Ado.BeginTran();
                if (dbclient.Updateable<T_Sys_UserInfo>(uInfo).ExecuteCommand() == 1)
                {
                    dbclient.CommitTran();
                    return new
                    {
                        state = true
                    };
                }
                else
                {
                    dbclient.RollbackTran();
                    return new
                    {
                        state = false,
                        tip = "修改失败"
                    };
                }
            }
            else
            {
                return new
                {
                    state = false,
                    tip = "找不到对应的人员"
                };
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="oldPwd"></param>
        /// <param name="newPwd"></param>
        /// <returns></returns>
        public dynamic UpdatePwd(string oldPwd, string newPwd)
        {
            var dbclient = this.Db!.GetDbContext(string.Empty);
            var uInfo = dbclient.Queryable<T_Sys_UserInfo>().Where(t => t.ID == this.CurrentUser!.UserID).First();
            if (uInfo != null)
            {
                if (uInfo.Password == Des.Encrypt(oldPwd))
                {
                    dbclient.Ado.BeginTran();
                    uInfo.Password = Des.Encrypt(newPwd);
                    if (dbclient.Updateable<T_Sys_UserInfo>(uInfo).ExecuteCommand() == 1)
                    {
                        dbclient.CommitTran();
                        return new
                        {
                            state = true
                        };
                    }
                    else
                    {
                        dbclient.RollbackTran();
                        return new
                        {
                            state = false,
                            tip = "修改失败"
                        };
                    }
                }
                else
                {
                    return new
                    {
                        state = false,
                        tip = "原密码不正确"
                    };
                }
            }
            else
            {
                return new
                {
                    state = false,
                    tip = "找不到对应的人员"
                };
            }


        }
        /// <summary>
        /// 获取人员对应的组织机构信息
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public dynamic GetUserOrg(int userID)
        {
            return Db!.GetDbContext(string.Empty).Queryable<R_User_Org>().Where(t => t.UserID == userID).ToList();
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userList"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool Delete(List<int> userList, ref string errorMsg)
        {
            var client = this.Db!.GetDbContext(string.Empty);
            string error = null;
            bool result = _messagePublisher.ExecuteDBAndPublish(client.Ado, () =>
            {
                //删除组织关系
                client.Deleteable<R_User_Org>().Where(t => userList.Contains(t.UserID)).ExecuteCommand();

                //删除角色对应关系
                client.Deleteable<R_Role_User>().Where(t => userList.Contains(t.UserID)).ExecuteCommand();

                //删除用户信息
                if (client.Deleteable<T_Sys_User>(userList).ExecuteCommand() == userList.Count())
                {
                    _messagePublisher.PublishWithDefaultCallback(MessageConstant.DeleteUser, userList);//推送数据
                    return true;
                }
                else
                {
                    error = "用户数据删除失败";
                    return false;
                }
            });
            if (!result)
            {
                errorMsg = error;
            }
            return result;
            //var dbclient = this.Db!.GetDbContext(string.Empty);
            //dbclient.BeginTran();

            ////删除组织关系
            //dbclient.Deleteable<R_User_Org>().Where(t => userList.Contains(t.UserID)).ExecuteCommand();

            ////删除角色对应关系
            //dbclient.Deleteable<R_Role_User>().Where(t => userList.Contains(t.UserID)).ExecuteCommand();

            ////删除用户信息
            //if (dbclient.Deleteable<T_Sys_User>(userList).ExecuteCommand() == userList.Count())
            //{
            //    dbclient.CommitTran();
            //    _messagePublisher.PublishWithDefaultCallback(MessageConstant.User, userList);//推送数据
            //    return true;
            //}
            //else
            //{
            //    errorMsg = "用户数据删除失败";
            //    dbclient.RollbackTran();
            //    return false;
            //}
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        public object GetUserInfo()
        {
            using (var db = Db.GetDbContext(string.Empty))
            {
                T_LoginLog log = db.Queryable<T_LoginLog>().Where(z => z.UserID == CurrentUser.UserID).OrderBy(z => z.LoginTime, OrderByType.Desc).First();
                var logtime = DateTime.Now;
                if (log != null)
                {
                    logtime = log.LoginTime;
                }
                var listuser = db.Queryable<T_Sys_User, R_User_Org, Organize, Post, T_CodeItem>((sa, sb, sc, sd, se) => new object[] {
                JoinType.Left,sa.ID==sb.UserID,
                JoinType.Left,sb.OrgID==sc.ID,
                JoinType.Left,sb.PostID==sd.ID,
                JoinType.Left,sa.UserType==se.CodeValue
                }).Where((sa, sb, sc, sd, se) => sa.ID == CurrentUser.UserID).Select((sa, sb, sc, sd, se) => new
                {
                    UserName = sa.UserName,
                    RealName = sa.DisplayName,
                    UserType = se.CodeText,
                    Depart = sc.OrgName,
                    Post = sd.PostName,
                    LoginTime = logtime
                }).First();
                return listuser;
            }
        }

        #region 根据多个机构Id集合获取多个机构下人员
        /// <summary>
        /// 根据多个机构Id集合获取多个机构下人员
        /// </summary>
        /// <param name="Param">请求参数</param>
        /// <returns></returns>
        public async Task<dynamic> GetOrgUserList(PublicParam Param)
        {
            ResultParam resultParam = new ResultParam();
            using (var db = Db.GetDbContext(String.Empty))
            {
                List<int> userIDList = new List<int>();
                if (!string.IsNullOrEmpty(Param.MainId) || (Param.IdList != null && Param.IdList.Count > 0))
                {
                    List<int> MainIdList = new List<int>();
                    if (Param.IdList != null && Param.IdList.Count > 0)
                    {
                        MainIdList = Param.IdList;
                    }
                    else
                    {
                        var MainIds = Param.MainId.Split(',');
                        foreach (var item in MainIds)
                        {
                            MainIdList.Add(int.Parse(item));
                        }
                    }
                    var UserIDList = db.Queryable<R_User_Org>().Where(t => MainIdList.Contains(t.OrgID)).Select(t => t.UserID).Distinct().ToList();
                    if (UserIDList.Count > 0)
                    {
                        var List = db.Queryable<T_Sys_User>().WhereIF(MainIdList.Count > 0, t => UserIDList.Contains(t.ID))
                            .WhereIF(!string.IsNullOrEmpty(Param.KeyWord), z => z.UserName.Contains(Param.KeyWord!) || z.UserCode.Contains(Param.KeyWord!))
                            .WhereIF(Param.IntList != null && Param.IntList.Any(), z => Param.IntList!.Contains(z.ID))
                            .WhereIF(Param.StringList != null && Param.StringList.Any(), z => Param.StringList!.Contains(z.UserCode))
                            .WhereIF(Param.CodeList != null && Param.CodeList.Any(), z => !Param.CodeList!.Contains(z.UserCode));
                        resultParam.PageCount = List.Count();
                        if (Param.PageSize > 0)
                        {
                            resultParam.Data = List.OrderBy(t => t.CreateTime, OrderByType.Desc).ToPageList(Param.PageIndex, Param.PageSize);
                        }
                        else
                        {
                            resultParam.Data = List.OrderBy(t => t.CreateTime, OrderByType.Desc).ToList();
                        }
                        resultParam.Code = 200;
                        resultParam.Msg = "成功";
                    }
                }
            }
            return resultParam;
        }
        #endregion

        #region 根据多个人员Id集合获取多个机构
        /// <summary>
        /// 根据多个人员Id集合获取多个机构
        /// </summary>
        /// <param name="Param">请求参数</param>
        /// <returns></returns>
        public async Task<dynamic> GetUserOrgList(PublicParam Param)
        {
            ResultParam resultParam = new ResultParam();
            using (var db = Db.GetDbContext(String.Empty))
            {
                if (Param.UserIdList.Count > 0)
                {
                    //var User_OrgList = db.Queryable<T_Sys_User, R_User_Org, Organize>((sa, sb, sc) => new object[] {
                    //JoinType.Left,sa.ID==sb.UserID,
                    //JoinType.Left,sb.OrgID==sc.ID
                    //}).Where((sa, sb, sc) => Param.UserIdList.Contains(sa.ID)).Select((sa, sb, sc) => new
                    //{
                    //    ID = sa.ID,
                    //    UserCode = sa.UserCode,
                    //    UserName = sa.UserName,
                    //    PropPath = sc.PropPath,
                    //    OrgId = sc.ID
                    //}).ToList();

                    var User_OrgList = db.Queryable<R_User_Org>().Where(t => Param.UserIdList.Contains(t.UserID)).Distinct().ToList();

                    if (User_OrgList.Count > 0)
                    {
                        List<dynamic> NewList = new List<dynamic>();
                        foreach (var User_Org in User_OrgList)
                        {
                            var UserList = db.Queryable<T_Sys_User>().Where(t => t.ID == User_Org.UserID).ToList();
                            if (UserList.Count > 0)
                            {
                                List<int> OrgList = new List<int>();
                                var OrgNewList = db.Queryable<Organize>().Where(t => t.ID == User_Org.OrgID).ToList();
                                if (OrgNewList.Count > 0)
                                {
                                    var OrgNew = (OrgNewList[0].PropPath.TrimStart('/') + OrgNewList[0].ID).Split('/');

                                    foreach (var Org in OrgNew)
                                    {
                                        OrgList.Add(int.Parse(Org));
                                    }
                                }
                                NewList.Add(new
                                {
                                    ID = UserList[0].ID,
                                    UserCode = UserList[0].UserCode,
                                    UserName = UserList[0].UserName,
                                    OrgList = OrgList
                                });
                            }
                        }

                        resultParam.Data = NewList;
                        resultParam.Code = 200;
                        resultParam.Msg = "成功";
                    }
                }
            }
            return resultParam;
        }
        #endregion

        #region 获取所有用户信息
        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns></returns>
        public async Task<dynamic> GetUserList()
        {
            ResultParam resultParam = new ResultParam();
            using (var db = Db.GetDbContext(String.Empty))
            {
                resultParam.Code = 200;
                resultParam.Data = db.Queryable<T_Sys_User>().ToList();
            }
            return resultParam;
        }
        #endregion

        #region 获取组织与人员
        /// <summary>
        /// 获取组织与人员
        /// </summary>
        /// <param name="Param">请求参数</param>
        /// <returns></returns>
        public async Task<dynamic> GetOrgAndUser(PublicParam Param)
        {
            ResultParam resultParam = new ResultParam();
            using (var db = Db.GetDbContext(String.Empty))
            {
                List<Organize> treelist = new List<Organize>();
                //var all = db.Queryable<Organize>().Where(z => z.Deleted == 0).OrderBy(z => z.OrderCode).ToList();
                var all = db.Queryable<Organize>().OrderBy(z => z.OrderCode).ToList();
                foreach (var item in all)
                {
                    var UserIDList = db.Queryable<R_User_Org>().Where(t => t.OrgID == item.ID && t.UserID != CurrentUser.UserID).Select(t => t.UserID).Distinct().ToList();
                    item.UserList = "[]";
                    if (UserIDList.Count > 0)
                    {
                        var UserList = db.Queryable<T_Sys_User>().Where(t => UserIDList.Contains(t.ID))
                            .WhereIF(!string.IsNullOrEmpty(Param.KeyWord), z => z.UserName.Contains(Param.KeyWord) || z.UserCode.Contains(Param.KeyWord)).ToList();
                        if (UserList != null && UserList.Count > 0)
                        {
                            item.UserList = UserList;
                        }
                    }
                    var parent = all.Where(z => z.ID == item.ParentID).FirstOrDefault();
                    if (parent != null)
                    {
                        if (parent.Children == null)
                        {
                            parent.Children = new List<Organize>();
                        }
                        parent.Children.Add(item);
                    }
                    else
                    {
                        treelist.Add(item);
                    }
                }
                resultParam.Data = treelist;
                resultParam.Code = 200;
                resultParam.Msg = "成功";
            }
            return resultParam;
        }
        #endregion
    }
}
